package top.lingkang.finalvalidated.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author lingkang
 * Created by 2024/1/28
 * 自定义校验处理
 */
public class CustomValidHandle extends ValidHandle {
    private static final Logger log = LoggerFactory.getLogger(CustomValidHandle.class);
    protected Class<?>[] groups;

    /**
     * 初始化构造函数
     *
     * @param validVal   对象属性
     * @param annotation 自定义的注解对象
     */
    public CustomValidHandle(ValidVal validVal, Annotation annotation) {
        super(validVal, annotation);

        try {
            Field gField = annotation.getClass().getDeclaredField("groups");
            gField.setAccessible(true);
            groups = (Class<?>[]) gField.get(annotation);
        } catch (Exception e) {
            groups = new Class<?>[0];
            log.warn("Can't get \"Class<?>[] groups() default {};\" method from custom annotation");
        }
    }

    /**
     * 校验失败时，建议抛出 {@link top.lingkang.finalvalidated.error.ValidatedException} 异常
     *
     * @param target 待校验对象
     */
    @Override
    public void valid(Object target) {
        // 在此执行对 target 的校验
        // 取值：Object value = validVal.getValGet().get(target);、
        throw new UnsupportedOperationException("请实现自定义注解的校验");
    }

    @Override
    public Class<?>[] getGroups() {
        return groups;
    }
}
